﻿using System;
using System.Drawing;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace FaceIdentifier
{
    public partial class AddFace : Form
    {
        private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(FaceApi));
        private string Repository = "人脸库";
        private FaceApi _faces;
        private Bitmap _bitmap;

        public AddFace()
        {
            InitializeComponent();
        }

        public void Init(Bitmap bitmap, FaceApi faces)
        {
            _bitmap = bitmap;
            _faces = faces;
        }

        private void AddFace_Load(object sender, EventArgs e)
        {
            pictureBox1.Image = _bitmap;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text))
            {
                MessageBox.Show(@"用户编号不可为空");
                return;
            }

            if (string.IsNullOrEmpty(textBox2.Text))
            {
                MessageBox.Show(@"用户姓名不可为空");
                return;
            }

            var personSn = textBox1.Text.Trim();
            var personName = textBox2.Text.Trim();

            Regex rgx = new Regex("\\d{5,10}");
            if (!rgx.IsMatch(personSn))
            {
                MessageBox.Show(@"用户编号为5-10位纯数字");
                return;
            }

            try
            {
                
                var fileName = Repository + "/" + personSn + "_" + personName + ".jpg";
                var fi = new FileInfo(fileName);
                if (fi.Exists) fi.Delete();
                using(Bitmap img = new Bitmap(_bitmap.Width, _bitmap.Height))
                {
                    using(Graphics g = Graphics.FromImage(img))
                    {
                        g.DrawImage(pictureBox1.Image, 0, 0);
                    }
                    img.Save(fileName);
                    _faces.Add(personSn, img);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("添加失败", @"错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Close();
            }
        }

        private void AddFace_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                _bitmap?.Dispose();
            }
            catch (Exception ex)
            {
                Log.Error("关闭添加人脸对话框异常", ex);
            }
        }
    }
}